package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.auth.feign.MemberFeignService;

import com.atguigu.gulimall.auth.vo.SocialUser;
import com.atguigu.gulimall.common.constant.AuthServerConstant;
import com.atguigu.gulimall.common.utils.HttpUtils;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Controller
public class Oauth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @RequestMapping("oauth2.0/gitee/success")
    public String authorize(String code, HttpSession session, RedirectAttributes attributes) throws Exception {
        //1.使用code换区token，换取成功则继续进行2，否则重定向到登录页
        HashMap<String, String> query = new HashMap<>();
        query.put("client_id", "1556078e239e266f88277a7bbec25ec30a5e33b9c02107ac227b6ddfa3ffad7c");
        query.put("client_secret", "c81200421cec3e0a87e20e8e8fa3482927d478f18ced992c69f3d46a995b4229");
        query.put("grant_type", "authorization_code");
        query.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        query.put("code", code);

        //2.发送post
        //https://gitee.com/oauth/token?

        HttpResponse response = HttpUtils.doPost("https://gitee.com",
                "/oauth/token",
                "post",
                new HashMap<String, String>(),
                query,
                new HashMap<String, String>());
        Map<String, String> errors = new HashMap<>();
        if (response.getStatusLine().getStatusCode() == 200) {
            //2. 调用member远程接口进行oauth登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {
            });
            R login = memberFeignService.oauth2Login(socialUser);
            //2.1 远程调用成功，返回首页并携带用户信息
            if (login.getCode() == 0) {
                // session 子域共享问题
                MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息" + data.toString());
                // TODO 1.默认发的令牌，session = dakadja；作用域：当前域， 解决子域session共享问题
                // TODO 2.使用json的序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://gulimall.com";
            }else {
                //2.2 否则返回登录页
                errors.put("msg", "登录失败，请重试");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            errors.put("msg", "获得第三方授权失败，请重试");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
